import React, {
  FC,
  ReactElement,
  useEffect,
  useReducer,
  useCallback,
} from 'react'
import { Act_type, IState, ITodo } from '../../types'
import TdInput from './child/tdInput'
import todoReducer from './store'
import IdItem from './child/tdItem'
function initList(todoList: ITodo[]): IState {
  return {
    todoList,
  }
}
const TdList: FC = (): ReactElement => {
  const [state, dispatch] = useReducer(todoReducer, [], initList)
  useEffect(() => {
    console.log('first')
    dispatch({
      type: Act_type.INIT_DATA,
      payload: JSON.parse(localStorage.getItem('todo_list') || '[]'),
    })
  }, [])

  useEffect(() => {
    console.log('todoList,up')
    localStorage.setItem('todo_list', JSON.stringify(state.todoList))
  }, [state.todoList])

  const addTodo = useCallback((obj: ITodo): void => {
    dispatch({
      type: Act_type.ADD_TODO,
      payload: obj,
    })
  }, [])
  const removeTodo = useCallback((id: number): void => {
    dispatch({
      type: Act_type.REMOVE_TODO,
      payload: id,
    })
  }, [])
  const toggleTodo = useCallback((id: number): void => {
    dispatch({
      type: Act_type.TOGGLE_TODO,
      payload: id,
    })
  }, [])
  return (
    <div>
      <TdInput addTodo={addTodo} />
      <ul>
        {state.todoList &&
          state.todoList.map((v) => (
            <IdItem
              todo={v}
              key={v.id}
              toggleTodo={toggleTodo}
              removeTodo={removeTodo}
            />
          ))}
      </ul>
    </div>
  )
}
export default TdList
